// src/services/apiService.js
import axios from "axios";

/**
 * 获取详细指标数据
 * @param {string} zhibiao - 指标名称
 * @param {Array} selectedData - 选中的数据项数组
 * @returns {Promise<Array>} - 处理后的数据数组
 */
export const fetchXiangxiData = async (zhibiao, selectedData) => {
    try {
        const requests = selectedData.map(item =>
            axios({
                url: '/xiangxi',
                method: 'GET',
                headers: {
                    Authorization: "Bearer " + localStorage.getItem("jwt_token")
                },
                params: {
                    zhibiao: zhibiao,
                    code: item.xxdm,
                    xnzymc: item.xnzymc
                }
            }).catch(error => {
                console.error("请求失败:", error);
                return null;
            })
        );

        const responses = await Promise.all(requests);
        const validData = responses.filter(res => res !== null);

        return validData
    } catch (error) {
        console.error("获取详细数据失败:", error);
        throw error;
    }
};

/**
 * 处理数据数组，提取单对象数组中的对象
 * @param {Array} arr - 原始数组
 * @returns {Array} - 处理后的数组
 */
export const processTableData = (arr) => {
    return arr
        .map(item => {
            if (Array.isArray(item) && item.length === 1 && typeof item[0] === 'object' && item[0] !== null) {
                return item[0];
            }
            return item;
        })
        .filter(item => item !== undefined)
        .flatMap(item => (Array.isArray(item) ? item : [item]));
};
